<template>
  <a-comment>
    <template v-slot:avatar>
      <img
        style="border-radius:50%;width: 32px;height: 32px;"
        :src="$http.baseURL+'/public/pic/'+$root.avatar"
      />
    </template>
    <template v-slot:content>
      <a-form-item>
        <a-textarea :rows="4" v-model:value="value" />
      </a-form-item>
      <a-form-item>
        <a-button html-type="submit" :loading="submitting" type="primary" @click="handleSubmit">
          提交
        </a-button>
      </a-form-item>
    </template>
  </a-comment>
  <a-list
    v-if="comments.length"
    :data-source="comments"
    :pagination="pagination"
    :header="`${comments.length} ${comments.length > 1 ? 'replies' : 'reply'}`"
    item-layout="horizontal"
  >
    <template v-slot:renderItem="{ item, index }">
      <a-list-item>
        <a-comment
          :author="item.nickname"
          :avatar="$http.baseURL+'/public/pic/'+item.avatar"
          :content="item.content"
          :datetime="item.date"
        >
         <template v-slot:actions v-if="$root.isAdmin||item.userId==$root.userId">
            <span @click="deleteComment(item)">删除</span>
          </template>
        </a-comment>
      </a-list-item>
    </template>
  </a-list>
</template>
<script>
export default {
  data() {
    return {
      comments: [],
      submitting: false,
      value: '',
      pagination:{
        current:1,
        pageSize: 10,
        total:0,
        onChange: (page, pageSize) => {
          this.pagination.current = page
          this.search()
        }
      }
    };
  },
  created(){
    this.search()
  },
  methods: {
    deleteComment(obj){
      this.$confirm({
        title: `确认删除留言 ${obj.content} 吗？`,
        content: '删除后不可恢复',
        okText: '确定',
        cancelText: '取消',
        onOk:() => {
          this.$http.get('/deleteComment',{id:obj.id}).then(_=>{
            this.$message.success(`删除留言 ${obj.content} 成功`)
            this.search()
          })
        },
      });
    },
    search(){
      var obj = {
        current: this.pagination.current,
        pageSize: this.pagination.pageSize,
      }
      this.$http.get('/getComment',obj).then(_=>{
        this.comments = _.data
        this.pagination.total = _.total
      })
    },
    handleSubmit() {
      if (!this.value.trim()) {
        this.$message.error('请输入内容')
        return;
      }
      this.submitting = true;
      var obj = {
        avatar: this.$root.avatar,
        nickname: this.$root.nickname,
        content: this.value,
      }
      this.$http.get('/addComment',obj).then(_=>{
        this.$message.success('留言成功！')
        this.search()
        this.submitting = false;
        this.value = '';
      })
    }
  }
};
</script>